package hsl.study.config;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import hsl.study.entities.ChatMessageDO;
import hsl.study.mapper.ChatMessageMapper;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: hsl
 * @CreateDate: 2025/7/31 17:59
 * @Version: 1.0
 */

@Component
public class MySQLChatMemory implements ChatMemory {

    @Resource
    private ChatMessageMapper chatMessageMapper;

    @Override
    public void add(String conversationId, Message message) {
        ChatMessageDO chatMessageDO = new ChatMessageDO();
        chatMessageDO.setConversationId(conversationId);
        chatMessageDO.setRole(message.getMessageType().name());
        chatMessageDO.setContext(message.getText());

        chatMessageMapper.insert(chatMessageDO);
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        messages.forEach(message -> add(conversationId, message));
    }

    @Override
    public List<Message> get(String conversationId) {
        LambdaQueryWrapper<ChatMessageDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ChatMessageDO::getConversationId, conversationId);

        return chatMessageMapper.selectList(lambdaQueryWrapper)
                .stream()
                .limit(20)
                .map(chatMessageDO -> new UserMessage(chatMessageDO.getContext()))
                .collect(Collectors.toList());
    }

    @Override
    public void clear(String conversationId) {
        LambdaQueryWrapper<ChatMessageDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ChatMessageDO::getConversationId, conversationId);

        chatMessageMapper.delete(lambdaQueryWrapper);
    }
}
